import React, {useEffect, useState, useMemo} from "react"; // 引入 useMemo
import {inject, observer} from "mobx-react";
import {getUser, getVersionInfo} from "tiklab-core-ui"; // 引入 getVersionInfo
import {Dropdown, Space, Tooltip} from "antd";
import {ShowWorkspaceIcon, toWorkspaceDetail} from "../workspace/components/WorkspaceFn";
import {SYSTEM_ROLE_STORE} from 'tiklab-privilege-ui/es/store'
import workspaceRecentStore from "../workspace/store/WorkspaceRecentStore";
import IconCommon from "../../common/IconCommon";
import {useHistory} from "react-router";
import "./workspaceDetailStyle.scss"
import "../workspace/components/workspace.scss"
import "../../common/commonStyle.scss"
import "../../api/http/definition/components/apxMethod.scss"
import "../../support/share/components/shareStyle.scss"
import {HomeOutlined} from "@ant-design/icons";
import LeftMenuCommon from "../../common/LeftMenuCommon/LeftMenuCommon";

/**
 * 左侧导航展示
 */
const LeftNav = (props) =>{
    const {workspaceStore,systemRoleStore} = props;
    const {workspaceIcon,findWorkspace,findWorkspaceJoinList } = workspaceStore;
    const {workspaceRecent,findWorkspaceRecentPage}=workspaceRecentStore;

    // 使用 useMemo 缓存版本信息，避免不必要的重复获取
    const versionInfo = useMemo(() => getVersionInfo(), []);

    const menuData = [ // 菜单项数据
        {
            "icon":"layers",
            "name":"概况",
            "key":"overview",
            "router":"/workspace/overview"
        },
        {
            "icon":"kuaijieyingyon",
            "name":"接口调试",
            "key":"quickTest",
            "router":"/workspace/quickTest"
        },
        {
            "icon":"jiekou",
            "name":"接口",
            "key":"api",
            "router":"/workspace/apis"
        },
        {
            "icon":"fenxiang",
            "name":"分享",
            "key":"share",
            "router":"/workspace/share"
        },
        {
            "icon":"pingshen",
            "name":"评审",
            "key":"review",
            "router":"/workspace/review",
            "extension":true // 标记为扩展功能项
        },
        {
            "icon":"statistics",
            "name":"统计",
            "key":"statistics",
            "router":"/workspace/statistics/trend",
            "extension":true // 标记为扩展功能项
        }
    ];

    const history = useHistory();
    const [visible, setVisible] = useState(false); // 控制切换项目下拉框的显示
    const workspaceId = localStorage.getItem("workspaceId");
    const [recentList, setRecentList] = useState([]); // 最近访问的项目列表
    const [workspaceName, setWorkspaceName] = useState(); // 当前项目名称

    useEffect(()=>{
        // 初始化加载当前项目信息和权限
        const initData = async () => {
            if (workspaceId) {
                let info = await findWorkspace(workspaceId);
                if (info) {
                    setWorkspaceName(info.workspaceName);
                }
                // 确保 systemRoleStore 和相关方法已正确注入和可用
                if (systemRoleStore && typeof systemRoleStore.getInitProjectPermissions === 'function') {
                    systemRoleStore.getInitProjectPermissions(getUser().userId, workspaceId);
                }
            }
        };
        initData();
    },[workspaceId, findWorkspace, systemRoleStore]); // 依赖项，当它们变化时重新执行

    // 打开/关闭切换项目下拉框，并加载最近项目列表
    const openToggleWorkspace = async () =>{
        setVisible(prev => !prev); // 切换显示状态
        if (!visible) { // 仅在下拉框将要打开时加载数据
            let userId = getUser().userId;
            let params = {
                pageParam: {
                    pageSize: 5,
                    currentPage:1
                },
                userId:userId
            };
            let fetchedRecentList = await findWorkspaceRecentPage(params);

            // 如果最近项目不足5个，则从加入的项目中补充
            if (fetchedRecentList.length < 5) {
                let additionalList = await findWorkspaceJoinList({userId:userId});
                // 去重
                additionalList = additionalList.filter(item =>
                    !fetchedRecentList.some(existingItem => existingItem.id === item.id)
                );
                // 合并并截取
                fetchedRecentList = fetchedRecentList.concat(additionalList.slice(0, 5 - fetchedRecentList.length));
            }
            setRecentList(fetchedRecentList.slice(0, 5)); // 最终确保最多5个
        }
    };

    /**
     * 渲染切换项目的下拉视图
     * @param {boolean} isExpanded - 侧边栏是否展开
     */
    const toggleWorkspaceView =(isExpanded)=> (
        <div className={"ws-hover-box"} style={{left:`${isExpanded?"200px":"75px"}`}}>
            <div style={{ padding: "10px"}}>
                <div className={"ws-hover-box-title"}>切换项目</div>
                <div style={{height:"210px"}}>
                    {
                        recentList && recentList.map((item)=> {
                                return (
                                    <div
                                        className={`ws-hover-item ${item?.workspace?.id===workspaceId?"ws-toggle-ws-select":""}`}
                                        key={item?.workspace?.id}
                                        onClick={() => toggleWorkspace(item?.workspace?.id)}
                                    >
                                        <Space>
                                            <ShowWorkspaceIcon url={item?.workspace?.iconUrl} className={"workspace-icon icon-bg-border"}  width={30}/>
                                            {item?.workspace?.workspaceName}
                                        </Space>
                                    </div>
                                );
                            }
                        )
                    }
                </div>
            </div>
            <a className={"ws-toggle-repository_more"} onClick={()=>history.push("/workspaces")}>查看更多</a>
        </div>
    );

    /**
     * 切换项目逻辑
     * @param {string} newWorkspaceId - 要切换到的新项目ID
     */
    const toggleWorkspace = (newWorkspaceId)=>{
        toWorkspaceDetail(newWorkspaceId, workspaceRecent); // 执行切换项目的核心函数
        history.push('/workspace/overview'); // 切换后默认跳转到概览页
        setVisible(false); // 关闭下拉框
    };

    // 工作空间下拉切换组件
    const WorkspaceDropdown = ({isExpanded}) => (
        <li className="menu-box-nav-item-workspace">
            <Dropdown
                overlay={() => toggleWorkspaceView(isExpanded)} // 使用函数返回 overlay 内容
                trigger={['click']}
                open={visible}
                onOpenChange={openToggleWorkspace} // open 和 onOpenChange 控制下拉框状态和数据加载
            >
                {isExpanded ? (
                    <div className={`ws-icon-box menu-box-nav-item-isExpanded`} style={{padding: '15px 0 15px 22px'}}>
                        <div style={{"cursor": "pointer"}}>
                            <ShowWorkspaceIcon url={workspaceIcon} className="icon-l icon-bg-border" width={30}/>
                        </div>
                        <div className="text-ellipsis" style={{maxWidth: "100px"}}>{workspaceName}</div>
                        <IconCommon
                            style={{cursor: "pointer", width: "10px", height: "10px", marginLeft: "3px"}}
                            icon="xiala"
                        />
                    </div>
                ) : (
                    <Tooltip placement="right" title={workspaceName}>
                        <div className={`ws-icon-box menu-box-nav-item-not-isExpanded`} style={{padding: '15px 0 15px 22px'}}>
                            <div style={{"cursor": "pointer"}}>
                                <ShowWorkspaceIcon url={workspaceIcon} className="icon-x icon-bg-border" width={30}/>
                            </div>
                        </div>
                    </Tooltip>
                )}
            </Dropdown>
        </li>
    );

    // 返回主页按钮组件
    const HomeButton = ({isExpanded, themeColor}) => (
        <li
            className="menu-box-nav-item"
            style={{
                borderBottom: themeColor === "theme-default" ? "1px solid #e3e3e3" : "1px solid #f6f7f81a",
                margin: "0 0 10px 0"
            }}
            onClick={() => {
                history.push("/index");
                localStorage.setItem("LEFT_MENU_SELECT", "/index");
            }}
        >
            {isExpanded ? (
                <div className={`menu-box-nav-item-${themeColor} menu-box-nav-item-isExpanded`}>
                    <div className="menu-box-nav-item-detail">
                        <HomeOutlined style={{fontSize: '18px', margin: "0 5px 0 6px", color: "#777"}}/>
                    </div>
                    <div className="menu-box-nav-item-detail">返回主页</div>
                </div>
            ) : (
                <Tooltip placement="right" title="返回主页">
                    <div className={`menu-box-nav-item-${themeColor} menu-box-nav-item-not-isExpanded`}>
                        <div className="menu-box-nav-item-detail">
                            <HomeOutlined
                                style={{
                                    fontSize: '20px',
                                    margin: "0 5px 0 6px",
                                    color: themeColor === "theme-default" ? "#777" : "white"
                                }}
                            />
                        </div>
                    </div>
                </Tooltip>
            )}
        </li>
    );

    // 顶部差异化内容区（项目切换和返回主页）
    const showToggleRepository = (isExpanded, themeColor, isElectronWindows) => (
        <>
            {!isElectronWindows() && <WorkspaceDropdown isExpanded={isExpanded}/>}
            <HomeButton isExpanded={isExpanded} themeColor={themeColor}/>
        </>
    );

    return(
        <LeftMenuCommon
            menuData={menuData} // 菜单数据
            diffHeader={showToggleRepository} // 菜单顶部的特定内容
            workspaceId={workspaceId}
            settingRouter={"/workspace/setting"} // 设置页面的路由
            versionInfo={versionInfo} // 将版本信息传递给 LeftMenuCommon
        />
    );
};

export default inject("workspaceStore",SYSTEM_ROLE_STORE)(observer(LeftNav));